package com.adam.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserAuthorityRepository userAuthorityRepository;

    @Override
    //@Transactional避免懒加载关联对象时会话失效failed to lazily initialize a collection of role
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("=======执行自定义登录逻辑====");
        //校验用户名，实际环境中需要从数据库查询
//        if (!username.equals("admin")) {
//            throw new UsernameNotFoundException("用户不存在");
//        }
        //比较密码，实际需要从数据库取出原密码校验，框架会自动读取登录页面的密码
//        String password = passwordEncoder.encode("123456");
        //返回UserDetails，实际开发中可拓展UserDetails
//        return new User(username, password,
//                自定义权限
//                AuthorityUtils.commaSeparatedStringToAuthorityList("permission1"));
        User user = userRepository.findByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
//        List<UserAuthority> userAuthorities = userAuthorityRepository.findByUserId(user.getId());
        List<UserAuthority> userAuthorities = user.getUserAuthorities();
        System.out.println("userAuthorities is null?" + (userAuthorities == null));
        userAuthorities = userAuthorities == null ? new ArrayList<>() : userAuthorities;
        List<GrantedAuthority> grantedAuthorities = userAuthorities.stream().map(
                userAuthority -> new SimpleGrantedAuthority(userAuthority.getAuthority().name())
        ).collect(Collectors.toList());
        org.springframework.security.core.userdetails.User springUser = new org.springframework.security.core.userdetails.User(
                user.getUsername(), user.getPassword(), grantedAuthorities);
        return springUser;
    }
}
